﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace YJKArch.RoomRoofModule
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdRoomsBatchCreation : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			Autodesk.Revit.DB.Document document = cmdData.Application.ActiveUIDocument.Document;
			SortedList sortedLevels = this.GetSortedLevels(document);
			RoomsBatchCreationForm roomsBatchCreationForm = new RoomsBatchCreationForm(cmdData.Application.ActiveUIDocument.ActiveView.ViewName, sortedLevels);
			if (DialogResult.OK == roomsBatchCreationForm.ShowDialog())
			{
				double num = AssistFunc.mmToFeet(10.0);
				num *= num;
				List<Level> selectLevels = roomsBatchCreationForm.GetSelectLevels();
				Transaction transaction = new Transaction(document, "RoomsBatchCreation");
				transaction.Start();
				foreach (Level level in selectLevels)
				{
					foreach (object obj in document.get_PlanTopology(level).Circuits)
					{
						PlanCircuit planCircuit = (PlanCircuit)obj;
						if (!planCircuit.IsRoomLocated && planCircuit.Area >= num)
						{
							document.Create.NewRoom(null, planCircuit);
						}
					}
				}
				transaction.Commit();
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private SortedList GetSortedLevels(Autodesk.Revit.DB.Document doc)
		{
			SortedList sortedList = new SortedList();
			FilteredElementIterator elementIterator = new FilteredElementCollector(doc).OfClass(typeof(Level)).GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
				Level level = element as Level;
				if (level != null)
				{
					sortedList.Add(level.Elevation, level);
				}
			}
			return sortedList;
		}
	}
}
